/*
	Copyright (C) 2008 by Jean-François Geyelin
	jfgeyelin@gmail.com

	This program is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation; either version 2 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the
	Free Software Foundation, Inc.,
	51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/



#include "all.h"
#include "SurfaceHandler.h"
#include "DisplayString.h"
#include "globals.h"
#include "constants.h"
#include "handleEvents.h"
#import "url.h"

#ifndef NO_LIBCURL
#ifndef __APPLE__
    #include <curl/curl.h>
    #include <curl/types.h>
    #include <curl/easy.h>
#endif
#endif


int drawButtonInMenu(int mouseX, int mouseY, int x, int y, int w, int h, std::string str, SDL_Surface *destinationSurface, int type, int returnValue);
std::string getFullPathWithString(std::string fileName);



int postFileThread(void *parameter) {
#ifndef NO_LIBCURL


    PostThreadParameters *ptp = (PostThreadParameters *)parameter;

	std::string fileName = "record.txt";
    std::string url = URL_OF_SERVER"/AddReplay";
	std::string userAgent = USER_AGENT;

#ifndef __APPLE__

	/*****************
	 LINUX & WIN code
	 ******************/
    TEST_EXECUTION()
    CURL *curl;

    CURLcode res;

    struct curl_httppost *formpost=NULL;
    struct curl_httppost *lastptr=NULL;
    struct curl_slist *headerlist=NULL;
    char buf[] = "Expect:";

   /* Fill in the file upload field */

   curl_formadd(&formpost,
                &lastptr,
                CURLFORM_COPYNAME, "sendfile",
                CURLFORM_FILE, getFullPathWithString(fileName).c_str(),
                CURLFORM_END);
   curl_formadd(&formpost,
                &lastptr,
                CURLFORM_COPYNAME, "filename",
                CURLFORM_COPYCONTENTS, fileName.c_str(),
                CURLFORM_END);

    curl = curl_easy_init();
    headerlist = curl_slist_append(headerlist, buf);
    if (curl) {
        TEST_EXECUTION()
        curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
        curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
        curl_easy_setopt(curl, CURLOPT_USERAGENT, userAgent.c_str());
        res = curl_easy_perform(curl);
        TEST_EXECUTION()
        curl_easy_cleanup(curl);
        curl_formfree(formpost);
        curl_slist_free_all (headerlist);

    }
    else
    {
        LOG_ERROR("failed to \"curl_easy_init\".\n");
    }

#else

	/*****************
		OS X code
	 ******************/
	std::string command = "curl --user-agent "+userAgent+" -F sendfile=@"+getFullPathWithString(fileName)+" --url "+url;
	system(command.c_str());

#endif
    SDL_Delay(700);
    SDL_mutexP(ptp->mutex);
    ptp->postIsComplete = true;
    SDL_mutexV(ptp->mutex);
    TEST_EXECUTION()
#endif
    return 1;
}


bool postFileToServer(void) {
    SDL_Surface *screenSave;
    screenSave = SDL_CreateRGBSurface(SDL_HWSURFACE, screenSurface->w, screenSurface->h, 32, bmask, gmask, rmask, amask);
    SurfaceHandler::drawSurface(screenSurface, 0, 0, screenSave);

    bool scoreIsSent = false;

    PostThreadParameters ptp;
    ptp.postIsComplete = false;
    ptp.mutex = SDL_CreateMutex();

    SDL_Thread *thread;
    thread = SDL_CreateThread(postFileThread, &ptp);


    std::string s0 = "Sending score";
    std::string s1 = "Waiting for server";

    std::string s3 = "";

    int mouseX;
    int mouseY;
    bool mouseIsPressed;

    int time = 0;

    DisplayString::drawString3(s0.c_str(), (SCREEN_WIDTH-(FONT_SPACING*s0.length()))/2,SCREEN_HEIGHT/2 - 60);

    bool postIsComplete = false;
    quit = false;
    while (!quit && !postIsComplete) {

        SDL_mutexP(ptp.mutex);
        postIsComplete = ptp.postIsComplete;
        SDL_mutexV(ptp.mutex);

        time++;
        if (time>=200) {
            std::string s2 = "It is taking longer than usual.";
            DisplayString::drawString3(s2.c_str(), (SCREEN_WIDTH-(FONT_SPACING*s2.length()))/2,SCREEN_HEIGHT/2 - 10);
        }

        mouseIsPressed = SDL_GetMouseState(&mouseX,&mouseY)&SDL_BUTTON(1);

        std::string s4 = s1+s3;
        if (time % 10 == 0) {
            s3+=".";
            if (s3.length() == 4)
            s3 = "";
        }

        SDL_Rect r;
        r.x = 0;
        r.y = SCREEN_HEIGHT/2 - 30;
        r.w = SCREEN_WIDTH;
        r.h = 16;

        //SDL_FillRect(screenSurface, &r,SDL_MapRGB( screenSurface->format, 255,255,255 ));
        SurfaceHandler::drawSurface(screenSave, 0, 0, screenSurface);
        DisplayString::drawString3(s4.c_str(), (SCREEN_WIDTH-(FONT_SPACING*s1.length()))/2,SCREEN_HEIGHT/2 - 30);
        quit |= drawButtonInMenu(mouseX, mouseY, (SCREEN_WIDTH-50)/2, SCREEN_HEIGHT/2 + 30, 50 , 20 , "cancel", screenSurface,1,1) && mouseIsPressed;

        SDL_Flip( screenSurface );
		SDL_Delay(15);
		handleEvents();
    }

    while (quit) {
        quit = false;
        handleEvents();
        SDL_Delay(20);
    }

    SDL_Delay(100);

    SDL_FreeSurface(screenSave);


    if (scoreIsSent==false) {
        SDL_Delay(400);
        SDL_KillThread(thread);
        SDL_DestroyMutex(ptp.mutex);
        return false;
    }
    else {
        SDL_DestroyMutex(ptp.mutex);
        return true;
    }

}



